package network.urlconnection;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;

/**
 * 继承了URLConnection，内部封装了Socket
 * 在connect()方法中创建与远程服务器的Socket对象
 * @author glogo
 *
 */
public class EchoURLConnection extends URLConnection{

	private Socket connection = null;
	public final static int DEFAULT_PORT = 8000;
	
	protected EchoURLConnection(URL url) {
		super(url);
	}

	@Override
	public synchronized InputStream getInputStream() throws IOException {
		if(!connected)	connect();
		return connection.getInputStream();
	}
	
	@Override
	public OutputStream getOutputStream() throws IOException {
		if(!connected) connect();
		return connection.getOutputStream();
	}
	
	@Override
	public synchronized void connect() throws IOException {
		if(!connected){
			int port = url.getPort();
			if(port < 0 || port > 65536)	port = DEFAULT_PORT;
			this.connection = new Socket(url.getHost(), port);
			this.connected = true;
		}
	}

	public synchronized void disconnect() throws IOException{
		if(connected){
			this.connection.close();
			this.connected = false;
		}
	}
	
}
